package com.tudouji.project.bill.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.poi.ExcelTempUtil;
import com.tudouji.common.utils.poi.ExcelUtil;
import com.tudouji.framework.aspectj.lang.annotation.Log;
import com.tudouji.framework.aspectj.lang.enums.BusinessType;
import com.tudouji.framework.interceptor.annotation.RepeatSubmit;
import com.tudouji.framework.web.controller.BaseController;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.TableDataInfo;
import com.tudouji.project.bill.domain.AutoTransfer;
import com.tudouji.project.bill.domain.Sellform;
import com.tudouji.project.bill.domain.Sellitem;
import com.tudouji.project.bill.domain.Whoutform;
import com.tudouji.project.bill.domain.vo.SellformListRep;
import com.tudouji.project.bill.domain.vo.SellformRep;
import com.tudouji.project.bill.service.IAutoTransferService;
import com.tudouji.project.bill.service.ISellformService;
import com.tudouji.project.bill.service.ISellitemService;
import com.tudouji.project.bill.service.IWhoutformService;
import com.tudouji.project.bill.service.impl.SellformServiceImpl;
import com.tudouji.project.harvest.domain.Qaform;
import com.tudouji.project.harvest.service.IQaformService;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.wlinfo.domain.Wlinfo;
import com.tudouji.project.wlinfo.domain.Wlinfoitem;
import com.tudouji.project.wlinfo.service.IWlinfoService;
import com.tudouji.project.wlinfo.service.IWlinfoitemService;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 销售订单Controller
 *
 * @author wf
 * @date 2021-01-13
 */
@RestController
@RequestMapping("/bill/sellform")
public class SellformController extends BaseController {
    @Autowired
    private ISellformService sellformService;
    @Autowired
    private SellformServiceImpl sellformServiceI;
    @Autowired
    private IQaformService qaformService;
    @Autowired
    private IWlinfoService wlinfoService;
    @Autowired
    private IWlinfoitemService wlinfoitemService;
    @Autowired
    private ISellitemService sellitemService;
    @Autowired
    private IWhoutformService whoutformService;
    @Autowired
    private ExcelTempUtil excelTempUtil;
    @Autowired
    private IAutoTransferService autoTransferService;

    /**
     * 微信端列表,flowtempguid=34
     */
    @GetMapping("/wxList")
    public TableDataInfo wxList(Sellform sellform, String status, String functionType) {
        List<Sellform> list = sellformService.wxList(sellform, status, functionType);
        return getDataTable(list);
    }

    /**
     * 查询销售订单列表
     */
    @GetMapping("/baseList")
    public TableDataInfo baseList(Sellform sellform) {
        startPage();
        List<Sellform> list = sellformService.selectSellformList(sellform);
        return getDataTable(list);
    }

    /**
     * 查询销售订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Sellform sellform) {
        List<SellformListRep> list = sellformService.pagePCList(sellform, true);
        SellformListRep sum = sellformService.pagePCListSum(sellform);
        return getDataTable(list, sum);
    }

    /**
     * 查询销售订单列表
     */
    @RequestMapping(value = "/rptSellForm", method = RequestMethod.GET)
    public TableDataInfo rptSellForm(SellformRep entity, String stats, String paytypes) {
        startPage();
        if (StringUtils.isNotBlank(stats)) {
            String[] sts = stats.split(",");
            Integer[] s = (Integer[]) ConvertUtils.convert(sts, Integer.class);
            entity.setStats(s);
        }
        if (StringUtils.isNotBlank(paytypes)) {
            String[] pays = paytypes.split(",");
            Integer[] ps = (Integer[]) ConvertUtils.convert(pays, Integer.class);
            entity.setPaytypes(ps);
        }
        List<SellformRep> list = sellformService.findRpt(entity);
        return getDataTable(list);
    }

    /**
     * 导出销售订单
     */
    @Log(title = "销售订单", businessType = BusinessType.EXPORT)
    @GetMapping("/exportList")
    public AjaxResult exportList(Sellform sellform) {
        List<SellformListRep> list = sellformService.pagePCList(sellform, false);
//        ExcelUtil<SellformListRep> util = new ExcelUtil<>(SellformListRep.class);
//        return util.exportExcel(list, "sellform");
        return excelTempUtil.exportCommon(list, "销售订单");
    }

    /**
     * 导出销售报表
     */
    @Log(title = "销售订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SellformRep sellform) {
        List<SellformRep> list = sellformService.findRpt(sellform);
        ExcelUtil<SellformRep> util = new ExcelUtil<SellformRep>(SellformRep.class);
        return util.exportExcel(list, "sellform");
    }

    /**
     * 获取销售订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('bill:sellform:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid) {
        return AjaxResult.success(sellformService.selectSellformByGuid(guid));
    }

    /**
     * 新增销售订单
     */
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('bill:sellform:add')")
    @Log(title = "销售订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Sellform sellform) {
        return toAjax(sellformService.insertSellform(sellform));
    }

    /**
     * 修改销售订单
     */
    @PreAuthorize("@ss.hasPermi('bill:sellform:edit')")
    @Log(title = "销售订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Sellform sellform) {
        return toAjax(sellformService.updateSellform(sellform));
    }

    /**
     * 删除销售订单
     */
    @PreAuthorize("@ss.hasPermi('bill:sellform:remove')")
    @Log(title = "销售订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{guids}")
    public AjaxResult remove(@PathVariable String[] guids) {
        return toAjax(sellformService.deleteSellformByIds(guids));
    }

    /**
     * 微信--删除销售订单
     */
    @Log(title = "销售订单", businessType = BusinessType.DELETE)
    @PostMapping("del")
    public AjaxResult remove(Long id) {
        return sellformService.del(id);
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public AjaxResult detail(@RequestParam("orderid") Long id) {
        JSONObject json = new JSONObject();
        Sellform entity = new Sellform();
        entity.setId(id);
        try {
            entity = sellformService.findDetail(entity);
            String orderid = entity.getGuid();
            //货运损耗(运费结算时减去输入的重量)
            if (null != entity.getLoadweight() && null != entity.getUnnloadweight()) {
                BigDecimal sh = entity.getLoadweight().subtract(entity.getUnnloadweight());
                entity.setShWeight(sh);
            }
            Qaform qa = new Qaform();
            qa.setFoguid(orderid);
            List<Qaform> qaforms = qaformService.selectQaformList(qa);
            if (qaforms.size() > 0) {
                json.put("qaForm", qaforms.get(0));
            }
            //物流信息
            Wlinfoitem wlinfoitem = new Wlinfoitem();
            wlinfoitem.setOrderid(orderid);
            JSONArray wlinfos = new JSONArray();
            List<Wlinfoitem> wlinfoitems = wlinfoitemService.selectWlinfoitemList(wlinfoitem);
            List<Wlinfo> wlinfoList = new ArrayList<>();
            for (Wlinfoitem item : wlinfoitems) {
                String wlstatus = item.getWlstatus();
                Wlinfo wlinfo = new Wlinfo();
                if ("0".equalsIgnoreCase(wlstatus) || "1".equalsIgnoreCase(wlstatus)) {
                    wlinfo = this.wlinfoService.selectWlinfoById(item.getWlinfoid());
                }
                if ("2".equalsIgnoreCase(wlstatus)) {
                    wlinfo.setRelatedid(orderid);
                    List<Wlinfo> wls = this.wlinfoService.selectWlinfoList(wlinfo);
                    if (wls.size() > 0) {
                        wlinfo = wls.get(0);
                    }
                }

                wlinfoList.add(wlinfo);
            }
            json.put("wlinfos", wlinfoList);


            Wlinfo wl = new Wlinfo();
            wl.setRelatedid(orderid);
            List<Wlinfo> wls = wlinfoService.selectWlinfoList(wl);
            if (wls.size() > 0) {
                for (int i = 0; i < wls.size(); i++) {
                    if (2 != wls.get(i).getTranstype()) {
                        wl = wls.get(i);
                    }
                }
            }

            json.put("wlinfoaddress", wl);

            if (entity.getSpitems().size() > 0) {
                for (int i = 0; i < entity.getSpitems().size(); i++) {
                    Sellitem si = new Sellitem();
                    si.setSuitpackid(entity.getSpitems().get(i).getGuid());
                    List<Sellitem> sis = sellitemService.getSellItems(si);
                    entity.getSpitems().get(i).setSellitems(sis);
                }
            }

            List<Whoutform> whoutforms = sellformServiceI.getWhoutformAll(orderid);
            entity.setWhoutforms(whoutforms);
            json.put("status", "true");
            json.put("result", entity);
            return AjaxResult.success(json);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }
    }

    @RepeatSubmit
    @RequestMapping(value = "/review", method = RequestMethod.GET)
    public AjaxResult review(@RequestParam("orderid") Long id, @RequestParam("partitiontype") String partitiontype) {
        return sellformService.review(id, partitiontype);
    }

    /**
     * PC
     *
     * @return com.ecfund.base.model.Sellform
     * @auther shaodong
     * @desc 人员离职移交: 销售订单移交（未结束的所有订单）,权限移交,客户移交(销售经理下的客户)
     * @Date 16:16 2020/5/29
     * @Param []
     **/
    @RepeatSubmit
    @PostMapping("/usertransfer")
    public AjaxResult usertransfer(String touser, String fromuser) {
        return sellformService.usertransfer(touser, fromuser);
    }

    /**
     * 销售订单发起
     **/
    @RepeatSubmit
    @PostMapping("/save")
    public AjaxResult saveOrUpdate(@RequestBody Sellform entity, Long deptId, String fileIds, @RequestParam(required = false)Long taskid
            , @RequestParam(required = false)String opinion) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        return sellformService.saveOrUpdate(entity, deptId, fileIds, taskid, opinion, user);
    }

    /**
     * 销售出库
     **/
    @RepeatSubmit
    @PostMapping("/whout")
    public AjaxResult whout(Long taskid, @RequestBody Whoutform entity, Long id, String opinion, String fileIds,String opttype) {
        return sellformService.whout(id, entity, fileIds, opinion, taskid, opttype);
    }

    /**
     * @Description: 主管审批
     * @param innerOut 0外部(默认)1内部
     **/
    @RepeatSubmit
    @PostMapping("/zgsp")
    public AjaxResult  zgsp(Long id,Long taskid,String opinion,String fileIds, Integer innerOut){
        return sellformService.zgsp(id,taskid,opinion,fileIds, innerOut);
    }

    /**
     * @Description: 内部定价
     **/
    @RepeatSubmit
    @PostMapping("/nbdj")
    public AjaxResult nbdj(@RequestBody Sellform entity, String fileIds, @RequestParam(required = false)Long taskid
            , @RequestParam(required = false)String opinion){
//        return AjaxResult.success();
        return sellformService.nbdj(entity,taskid,opinion,fileIds);
    }

    /**
     * @Description: 内部定价审批
     **/
    @RepeatSubmit
    @PostMapping("/nbdjApproval")
    public AjaxResult nbdjApproval(Long id,Long taskid,String opinion,String fileIds){
        //TODO
        return sellformService.approval(id,taskid,opinion,fileIds);
    }

    /**
     * @Description: 调度
     * @Author: xiaxl
     * @Date:
     * @Param:
     * @return:
     **/
    @RepeatSubmit
    @PostMapping("/approval")
    public AjaxResult  approval(Long id,Long taskid,String opinion,String fileIds){
        return sellformService.approval(id,taskid,opinion,fileIds);
    }

    @RepeatSubmit
    @Log(title = "拒绝", businessType = BusinessType.OTHER)
    @PostMapping("/refuse")
    public AjaxResult refuse(Long taskid,Long id,String opinion,String fileIds,Long refuseNodeid,Long backUserid){
        return sellformService.refuse(id, fileIds, opinion, taskid,refuseNodeid,backUserid);
    }

    @RepeatSubmit
    @PostMapping("/partition")
    public AjaxResult partition(Long taskid,String fileIds,@RequestBody Sellform sellform){
        return sellformService.partition( taskid, fileIds,  sellform);
    }
    /**
     * @Description: 调度
     * @Author: xiaxl
     * @Date:
     * @Param:
     * @return:
     **/
    @RepeatSubmit
    @PostMapping("/dispatch")
    public AjaxResult dispatch(@RequestBody Sellform sellform,Long taskid,String opinion,String fileIds){
        return sellformService.dispatch(sellform,taskid,opinion,fileIds);
    }
    /**
     * @Description: 分拆/调度
     * @Author: xiaxl
     * @return:
     * @param: taskid 任务id
     * @param: fileIds 附件id
     * @param: partitiontype 分拆标识（不用传递了）
     * @param opinion 审批意见
     **/
    @RepeatSubmit
    @PostMapping("/partOrDispatch")
    public AjaxResult partOrDispatch(Long taskid,String fileIds,@RequestBody Sellform sellform,String opinion){
        return sellformService.partOrDispatch( taskid, fileIds,  sellform,opinion);
    }

    @RepeatSubmit
    @Log(title = "反出库", businessType = BusinessType.OTHER)
    @PostMapping("/whoutBack")
    public AjaxResult whoutBack(Long taskid, Long id, String opinion, String fileIds) {
        return sellformService.whoutBack(id, fileIds, opinion, taskid);
    }


    @RepeatSubmit
    @Log(title = "充值", businessType = BusinessType.OTHER)
    @PostMapping("/recharge")
    public AjaxResult recharge(Long taskid, Long id, String opinion, String fileIds, @RequestBody Sellform sellform) {
        return sellformService.recharge(id, fileIds, opinion, taskid, sellform);
    }

    @RepeatSubmit
    @Log(title = "结算", businessType = BusinessType.OTHER)
    @PostMapping("/settle")
    public AjaxResult settle(Long taskid, Long id, String opinion, String fileIds, @RequestBody Sellform sellform) {
        return sellformService.settle(id, fileIds, opinion, taskid, sellform);
    }


    @Log(title = "结算错误处理", businessType = BusinessType.OTHER)
    @GetMapping(value = "/solveSettle/{id}")
    public AjaxResult solveSettle(@PathVariable("id") Long id) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Sellform sf = sellformServiceI.selectSellformById(id);
        sellformServiceI.settleOne(sf.getFinalamount(), user, sf);
        return AjaxResult.success();
    }

    /**
     * 销售派车
     */
    @RepeatSubmit
    @PostMapping("/sendCar")
    public AjaxResult sendCar(@RequestBody Wlinfo wlinfo, Long id, String fileIds, @RequestParam(required = false)Long taskid
            , @RequestParam(required = false)String opinion) {
        return wlinfoService.sendCar(wlinfo, id, fileIds, taskid, opinion);
    }

    /**
     * 获取当前采收组织、采收库房对应的销售出库的组织、库房
     * 通过auto_tranfer获取
     */
    @GetMapping(value = "/getAutoStoreRM")
    public AjaxResult getAutoStoreRM(String orgguid, String storeRMguid) {
        AutoTransfer cond = new AutoTransfer();
        cond.setFromOrgguid(orgguid);
        cond.setFromStrmguid(storeRMguid);
        AutoTransfer autoTransfer = autoTransferService.findDestAutoTransfer(cond);
        return AjaxResult.success(autoTransfer);
    }

    /**
     * 获取结算信息
     */
    @GetMapping(value = "/getSettlementInfo")
    public AjaxResult getSettlementInfo(Long id) {
        return sellformService.getSettlementInfo(id);
    }

}
